package tk.cful.servlets;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import tk.cful.core.DBManager;
import tk.cful.core.UserEntity;
import tk.cful.utils.DigestHelper;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

/**
 * UserEntity: Root
 * Date: 08.11.13
 * Time: 14:46
 */
@WebServlet(name = "UploadFileServlet", urlPatterns = {"/upload_file"})
public class UploadFileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private ServletFileUpload uploader = null;
    private Logger log = Logger.getLogger(UploadFileServlet.class.getName());

    public void init() throws ServletException {
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
        fileFactory.setRepository(filesDir);
        this.uploader = new ServletFileUpload(fileFactory);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long start = System.currentTimeMillis();
        HttpSession session = request.getSession(true);
        String userName = (String) session.getAttribute("user_name");
        boolean fileExist = false;
        if (userName == null || userName.equals(""))
            response.sendRedirect("/cful/login.html");

        //if (!ServletFileUpload.isMultipartContent(request)) {
        //    throw new ServletException("Content type is not multipart/form-data");
        //}

        try {
            String file = request.getParameter("file");
            String name = request.getParameter("name");
            long p1 = System.currentTimeMillis();
            log.info(String.valueOf(p1 - start));
            MessageDigest md = MessageDigest.getInstance("md5");
            md.reset();
            md.update(file.getBytes());
            File fileItem = new File(request.getServletContext().getAttribute("FILES_DIR") +
                    File.separator + DigestHelper.getInstance().encode(md.digest()));

            long p2 = System.currentTimeMillis();
            log.info("1: " + String.valueOf(p2 - p1));
            FileWriter writeFile = new FileWriter(fileItem);

            writeFile.write(file);
            writeFile.close();
            DBManager manager = DBManager.getInstance();
            UserEntity user = manager.findUserByName(userName);
            String path = File.separator + userName + File.separator + fileItem.getName();
            log.info("before");
            long p3 = System.currentTimeMillis();
            log.info(String.valueOf(p3 - p2));
            manager.addFile(manager.generateFileID(),
                    name,
                    path,
                    user.getUserID(),
                    fileItem.getName());
            log.info("after");
            long p4 = System.currentTimeMillis();
            log.info(String.valueOf(p4 - p3));
            /*List<FileItem> fileItemsList = uploader.parseRequest(request);
            Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
            while (fileItemsIterator.hasNext()) {
                FileItem fileItem = fileItemsIterator.next();

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") +
                        File.separator + userName + File.separator + fileItem.getName());
                fileExist = file.exists();
                fileItem.write(file);
                DBManager manager = DBManager.getInstance();
                UserEntity user = manager.findUserByName(userName);
                String path = File.separator + userName + File.separator + fileItem.getName();
                log.info("UploadFileServlet: before adding file");
                log.info(manager.generateFileID() +
                        " " + fileItem.getName() +
                        " " + path +
                        " " + user.getUserID());
                log.info("File: " + file.getName() + ", flag = " + fileExist);
                if (!fileExist) {
                    log.info("Adding to db");
                    manager.addFile(manager.generateFileID(),
                            fileItem.getName(),
                            path,
                            user.getUserID());
                }
                log.info("UploadFileServlet: after adding file");
            }      */

        /*} catch (FileUploadException e) {
            throw new ServletException(e);  */
        } catch (Exception e) {
            throw new ServletException(e);
        }
        response.sendRedirect("/cful/workspace");
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fileName = request.getParameter("fileName");
        String fileStr;
        if (fileName == null || fileName.equals("")) {
            throw new ServletException("File Name can't be null or empty");
        }
        DBManager dbManager = DBManager.getInstance();
        File file = new File(request.getServletContext().getAttribute("FILES_DIR") +
                File.separator + fileName);
        if (!file.exists()) {
            throw new ServletException("File doesn't exists on server.");
        }

        response.setContentType("plain/text");
        response.setCharacterEncoding("UTF-8");
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(
                new FileReader(file));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        fileStr = fileData.toString();
        //fileStr = dbManager.getNameByHashName(fileName) + "|" + fileStr;

        log.info("111: " + fileStr);
        ServletContext ctx = getServletContext();
        //InputStream fis = new FileInputStream(file);
        //String mimeType = ctx.getMimeType(file.getAbsolutePath());
        //response.setContentLength((int) file.length());
        //response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        ServletOutputStream os = response.getOutputStream();
        os.print(dbManager.getNameByHashName(fileName));
        os.print("|");
        os.print(fileStr);
        /*byte[] bufferData = new byte[1024];
        int read = 0;
        while ((read = fis.read(bufferData)) != -1) {
            os.write(bufferData, 0, read);
        } */
        os.flush();
        os.close();
        //fis.close();
    }
}
